<template>
  <div class="page-common-layout custom-knowledgeBase-container">
    <div class="result-body-warp">
      <!-- 测绘文件库 -->
      <div class="drawing-container">
        <div class="header">
          {{ menuName }}
          <icon-font
            class="add-file-button"
            type="icon-xinjianwenjianjia"
            @click="handleAdd(1)"
            v-action:chzlk_add
          ></icon-font>
        </div>
        <div class="condition">
          <a-input placeholder="请输入关键字" v-model="keyWord" />
          <div class="search-btn">
            <a-icon type="search" @click="handleFilterTree()" />
          </div>
        </div>
        <div class="tree-container">
          <a-spin :spinning="spinning">
            <a-empty v-if="treeData.length == 0" :description="false" />
            <a-tree
              v-else
              v-model="checkedKeys"
              show-icon
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childList',
                title: 'nodeName',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <!-- 自定义图标 -->
              <template slot="custom">
                <icon-font type="icon-wenjianjia-" />
              </template>
              <template slot="title" slot-scope="{ nodeName, uuid, pid }">
                <div class="custom-tree-title-warp">
                  <div class="title" :title="nodeName">
                    {{ nodeName }}
                  </div>
                  <div class="operate">
                    <!-- 新增 -->
                    <icon-font
                      type="icon-xinjianwenjianjia"
                      class="add-file-button"
                      @click.stop="handleAdd(1, uuid)"
                      v-action:chzlk_add
                    ></icon-font>
                    <!-- 编辑 -->
                    <a-icon
                      type="edit"
                      class="edit-btn"
                      @click.stop="editor({ uuid, pid }, 1)"
                      v-action:chzlk_edit
                    />
                    <!-- 修改 -->
                    <a-icon
                      type="delete"
                      class="delete-btn"
                      @click.stop="handleDelClick({ uuid }, 1)"
                      v-action:chzlk_delete
                    />
                  </div>
                </div>
              </template>
            </a-tree>
          </a-spin>
        </div>
      </div>
      <!-- 列表 -->
      <div class="right-container">
        <div class="header">
          <a-button
            type="primary"
            icon="plus"
            :disabled="!currentTreeNode.uuid"
            @click="handleAdd(2)"
            v-action:chzlk_add
          >
            新增
          </a-button>
          <div class="search-condition-warp">
            <div class="condition-warp">
              <a-input
                placeholder="请输入文件名称"
                v-model="condition.fileName"
                style="width:180px"
              />
              <!-- <a-select
                style="width: 180px"
                v-model="condition.type"
                placeholder="请选择类别"
                showSearch
                allowClear
                :filter-option="filterOption"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in typeSource"
                  :key="item.dicItemCode"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select> -->
              <a-date-picker
                mode="year"
                format="YYYY"
                valueFormat="YYYY"
                v-model="condition.year"
                :open="condition.isopen"
                placeholder="选择年份"
                @panelChange="yearPanel"
                @openChange="yearOpen"
                class="year-picker"
              />
            </div>
            <div class="button-warp">
              <a-button type="primary" icon="search" @click="handleSearch()">
                查询
              </a-button>
              <a-button icon="sync" @click="handleReset()">重置</a-button>
            </div>
          </div>
        </div>
        <div class="table-container">
          <!-- table -->
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            show-overflow
            show-header-overflow
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="tableLoading"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column
              title="名称"
              field="fileName"
              min-width="150"
              align="left"
            >
            </vxe-column>
            <vxe-column title="查看/下载" width="100">
              <template #default="{ row }">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    @click="previewFile(row)"
                  />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    class="download-btn"
                    @click="downloadFile(row)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="publishDate" title="发布日期"> </vxe-column>
            <vxe-column field="creator" title="创建人"> </vxe-column>
            <vxe-column field="operate" title="操作" fixed="right" width="100">
              <template #default="{ row }">
                <!-- 编辑 -->
                <a-tooltip placement="top" v-action:chzlk_edit>
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click="editor(row, 2)"
                  />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip placement="top" v-action:chzlk_delete>
                  <template slot="title">
                    删除
                  </template>
                  <a-icon
                    type="delete"
                    class="delete-btn"
                    @click="handleDelClick(row, 2)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 分页 -->
        <div class="pager-container">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>
    <!-- 编辑-->
    <edit-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      @cancel="handleCancel()"
      @ok="handleOk()"
      :customFooter="modalFooter"
      :extraParameter="extraForm"
    />
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </div>
</template>

<script>
// 测绘文件库
import moment from "moment";
import cloneDeep from "lodash.clonedeep";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { downloadDfs } from "@/utils/TopVUI";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
//编辑
import editForm from "@/pages/form/formPreview/edit.vue";
//附件
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode } from "@/api/common.js";
import {
  getBaseTreeList,
  getBasePage,
  deleteBaseTree,
  deleteBasePage,
} from "@/api/knowledgeBase";
export default {
  components: {
    IconFont,
    editForm,
    previewModal,
  },
  data() {
    return {
      //查询体条件
      condition: {
        //文件名称
        fileName: "",
        //类别
        type: undefined,
        //日期范围
        year: null,
        isopen: false,
      },
      //测绘文件库
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      cloneTreeData: [],
      currentTreeNode: {},
      keyWord: "",
      //table
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //编辑
      visible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "",
      modalFooter: {},
      //额外传参
      extraForm: {},
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //类别
      typeSource: [],
      //页面类型
      pageType: 7,
      spinning: false,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },

  mounted() {
    Promise.all([this.getTypeSelectData(), this.getTreeData()]);
  },
  methods: {
    deleteBaseTree,
    deleteBasePage,

    handleOpen(url) {
      window.open(url);
    },

    //预览
    previewFile(row) {
      let list = this.analysisPath(row.files);
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let list = this.analysisPath(row.files);
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },

    //关闭弹窗
    handleCancel() {
      this.visible = false;
    },
    //
    handleOk() {
      this.visible = false;
      let { tableUuid } = this;
      switch (tableUuid) {
        //   左侧树;
        case "E447AD6197A0477FA382343FF4FC1D76":
          this.getTreeData();
          break;
        //   右侧列表;
        case "267FC4BFEF16412EA2A9E83F473D5C7A":
          this.getTableData();
          break;
        default:
          break;
      }
    },

    // 新增
    async handleAdd(type, pid = "0") {
      this.modalFooter = {};
      this.visible = true;
      this.$refs.createModal.title = "新增";
      let { uuid, tenantCode } = this.currentTreeNode;
      switch (type) {
        //树新新增
        case 1:
          this.extraForm = {
            tableName: "archive_directory",
            pid: pid,
            type: this.pageType,
          };
          this.tableUuid = "E447AD6197A0477FA382343FF4FC1D76";
          break;
        //列表新增
        case 2:
          this.extraForm = {
            tableName: "archive_file",
            directory_uuid: uuid,
            tenant_code: tenantCode,
            directory_type: this.pageType,
          };
          this.tableUuid = "267FC4BFEF16412EA2A9E83F473D5C7A";
          break;
        default:
          break;
      }
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { addApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.save = addApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.loadData(this.tableUuid, "add", formJsonData);
    },

    //编辑
    async editor(record = {}, type) {
      let { uuid, directoryUuid, pid } = record;
      let { tenantCode } = this.currentTreeNode;
      this.modalFooter = {};
      this.visible = true;
      switch (type) {
        //树编辑
        case 1:
          this.extraForm = {
            tableName: "archive_directory",
            pid,
            type: this.pageType,
          };
          this.tableUuid = "E447AD6197A0477FA382343FF4FC1D76";
          break;
        //列表编辑
        case 2:
          this.extraForm = {
            tableName: "archive_file",
            directory_uuid: directoryUuid,
            tenant_code: tenantCode,
            directory_type: this.pageType,
          };
          this.tableUuid = "267FC4BFEF16412EA2A9E83F473D5C7A";
          break;
        default:
          break;
      }
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { editApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.update = editApiUrl ?? "/form/formDatabase/formUpdate";
      this.$refs.createModal.title = "编辑";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "edit",
          formJsonData,
          res
        );
      });
    },

    loadDataJson(tableUuid = "") {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },

    //删除
    handleDelClick(row, type) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          let apiUrl = "";
          switch (type) {
            //树删除
            case 1:
              apiUrl = "deleteBaseTree";
              break;
            //列表删除
            case 2:
              apiUrl = "deleteBasePage";
              break;
            default:
              break;
          }
          that[apiUrl]({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (type == 1) {
                  that.getTreeData();
                }
                if (type == 2) {
                  if (dataLength == 1 && that.pager.page > 1) {
                    that.pager.page -= 1;
                  }
                  that.getTableData();
                }
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.pager.page = 1;
      this.getTableData();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //查询类别下拉框
    getTypeSelectData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "standardSpecificationType" })
          .then((res) => {
            let { data } = res;
            this.typeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.typeSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询项目列表-树形
    getTreeData() {
      this.spinning = true;
      return new Promise((resolve, reject) => {
        getBaseTreeList({ type: this.pageType })
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.cloneTreeData = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.spinning = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childList");
      let item = flatData.find((v) => !v.childList || v.childList.length == 0);
      this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
      this.selectedKeys = [item.uuid];
      this.currentTreeNode = item;
      this.pager.page = 1;
      this.getTableData();
    },

    //查询分页数据
    getTableData() {
      this.tableLoading = true;
      let { page, pageSize } = this.pager;
      let { uuid } = this.currentTreeNode;
      let { fileName, type = "", year = "" } = this.condition;
      getBasePage({
        page,
        pageSize,
        pid: uuid,
        directoryType: this.pageType,
        fileName,
        type,
        year,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    handleSearch() {
      this.pager.page = 1;
      this.getTableData();
    },
    handleReset() {
      this.condition.fileName = "";
      this.condition.type = undefined;
      this.condition.year = "";
      this.handleSearch();
    },
    //选择年份
    yearPanel(e) {
      this.condition.year = moment(e).format("YYYY");
      this.condition.isopen = false;
    },
    yearOpen(status) {
      if (status) {
        this.condition.isopen = true;
      } else {
        this.condition.isopen = false;
      }
    },

    //查询图纸管理树
    handleFilterTree() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.treeData = this.filterTree(cloneData, "childList", (node) =>
        node.nodeName.includes(keyWord)
      );
    },
    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    moment,
  },
};
</script>

<style lang="less" scoped>
.custom-knowledgeBase-container {
  position: relative;
  .drawing-container {
    width: 400px;
    .condition {
      input {
        width: 368px;
      }
    }
  }
  .tree-container {
    overflow: hidden;
  }
}
</style>
